package Handlers

import (
	"backend/Service/SQL/MySQL"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

var HTTP_TIMEOUT = 1
var FILE_SAVE_PATH = "./"
var FILE_UPLOAD_SIZE int64 = 1

type Services_info_in_server struct {
	Service_type string   `json:"service_type"`
	Input_shape  []uint64 `json:"input_shape"`
	Output_shape []uint64 `json:"output_shape"`
	Models       []string `json:"models"`
}

// 获取数据库中保存的服务器列表
func get_servers() (servers []MySQL.Model_server, err error) {
	// 获取所有数据库记录
	result := MySQL.DB_conn_for_udcpp.Find(&servers)
	err = result.Error
	return
}

func get_servers_info() (ans *[]Model_info, err error) {
	models_info := make([]Model_info, 0)
	ans = &models_info
	// 获取服务器列表
	servers, err := get_servers()
	if err != nil {
		return
	}
	// 验证每一个服务器的状态和信息
	http_client := http.Client{Timeout: time.Duration(HTTP_TIMEOUT) * time.Millisecond}
	for _, server := range servers {
		addr := server.Addr
		resp, err := http_client.Get(fmt.Sprintf("http://%s/", addr))
		if err != nil {
			models_info = append(models_info, Model_info{Addr: addr, Status: false})
			continue
		}
		defer resp.Body.Close()
		// 读取模型服务的返回数据有问题
		b, err := io.ReadAll(resp.Body)
		if err != nil {
			models_info = append(models_info, Model_info{Addr: addr, Status: false})
			continue
		}
		// 根据模型服务器的返回信息获取可用的模型
		models := make([]Services_info_in_server, 0)
		err = json.Unmarshal(b, &models)
		if err != nil {
			models_info = append(models_info, Model_info{Addr: addr, Status: false})
			continue
		}
		// 更新剩余的参数
		for index1 := range models {
			for index2 := range models[index1].Models {
				models_info = append(models_info,
					Model_info{Addr: addr, Status: true,
						Model_name:  models[index1].Models[index2],
						Input_shape: models[index1].Input_shape, Output_shape: models[index1].Output_shape})
			}
		}
	}
	return
}
